package main

import (
	"log"
	"os"
	"strings"
	"sync"
)

var filesChan chan string
var wg sync.WaitGroup

func GetFiles(address string) {
	//获取目录下的所有文件
	files, _ := os.ReadDir(address)
	for _, file := range files {
		//如果是目录则递归处理
		if file.IsDir() {
			GetFiles(address + "/" + file.Name())
		} else {
			//不是则传送文件路径
			filesChan <- address + "/" + file.Name()
		}
	}
	//返回
	return
}

// 删除空目录
func DeleteNullDir(filePath string) {
	//检查是否为空目录
	idx := strings.LastIndex(filePath, "/")
	temp, _ := os.ReadDir(filePath[:idx])
	if len(temp) <= 0 {
		//删除空目录
		_ = os.Remove(filePath[:idx])
	}
}

// 依据后缀删除
func DeleteBySuffix(filePath string, char string) bool {
	if strings.HasSuffix(filePath, char) {
		_ = os.Remove(filePath)
		log.Printf("[info] delete " + filePath)
		return true
	}
	return false
}

// 依据前缀删除
func DeleteByPrefix(filePath string, char string) bool {
	idx := strings.LastIndex(filePath, "/")
	if strings.HasPrefix(filePath[idx+1:], char) {
		_ = os.Remove(filePath)
		log.Printf("[info] delete " + filePath)
		return true
	}
	return false
}

// 删除包含某字符的文件名
func DeleteByChar(filePath string, char string) bool {
	//区别处理
	if strings.Contains(filePath, "avatar") {
		return false
	}
	//删除包含某字符的文件名
	idx := strings.LastIndex(filePath, "/")
	if strings.Contains(filePath[idx+1:], char) {
		_ = os.Remove(filePath)
		log.Printf("[info] delete " + filePath)
		return true
	}
	return false
}

func HandleFile() {
	for {
		//接收文件路径
		file, ok := <-filesChan
		//channel关闭则退出
		if !ok {
			break
		}
		//文件检查与删除
		if DeleteByChar(file, "#") {
			DeleteNullDir(file)
			continue
		}
		if DeleteBySuffix(file, ".dat") {
			DeleteNullDir(file)
			continue
		}
		if DeleteBySuffix(file, ".shader") {
			DeleteNullDir(file)
			continue
		}
		if DeleteBySuffix(file, ".json") {
			DeleteNullDir(file)
			continue
		}
		if DeleteByPrefix(file, "Background") {
			DeleteNullDir(file)
			continue
		}
		if DeleteByPrefix(file, "UI") {
			DeleteNullDir(file)
			continue
		}
		if DeleteByPrefix(file, "Icon") {
			DeleteNullDir(file)
			continue
		}
		DeleteNullDir(file)
	}
}

// 删除后缀为dat的文件
func main() {
	//初始化通道
	filesChan = make(chan string, 100)
	//启动获取文件路径协程
	wg.Add(1)
	go func() {
		GetFiles(".")
		close(filesChan)
		wg.Done()
	}()
	//启动删除文件协程
	wg.Add(1)
	go func() {
		HandleFile()
		wg.Done()
	}()
	//同步关闭
	wg.Wait()
}